package wicketforge.converter.dialog;

import java.awt.*;
import java.util.regex.Pattern;

import javax.swing.*;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import wicketforge.converter.RegexPathConverter;
import com.intellij.openapi.ui.ValidationInfo;

public class RegexPathConverterDialog extends BasePathConverterDialog<RegexPathConverter> {

	private JTextField matcherField;
	private JTextField replacementField;

	public RegexPathConverterDialog(@NotNull final Component parent, final RegexPathConverter regexPathConverter) {
		super(parent, regexPathConverter, false);
		init();
		setTitle("Edit Regular Expression Path Converter");
	}

	@Nullable
	@Override
	protected JComponent createCenterPanel() {

		Box form = Box.createVerticalBox();
		form.add(new JLabel("Define regex to math and the replacement.", SwingConstants.LEFT));
		form.add(Box.createVerticalStrut(5));

		createNameField(form);
		form.add(Box.createVerticalStrut(5));

		Box matcherBox = Box.createHorizontalBox();
		matcherBox.add(new JLabel("RegEx to be matched:", SwingConstants.LEFT));
		matcherBox.add(Box.createHorizontalStrut(5));
		matcherField = new JTextField(getPathConverter().getPatter(), 30);
		matcherBox.add(matcherField);
		form.add(matcherBox);
		form.add(Box.createVerticalStrut(5));

		Box replaceBox = Box.createHorizontalBox();
		replaceBox.add(new JLabel("Specify replacement ($n can be used):", SwingConstants.LEFT));
		replaceBox.add(Box.createHorizontalStrut(5));
		replacementField = new JTextField(getPathConverter().getReplacement(), 30);
		replaceBox.add(replacementField);
		form.add(replaceBox);

		return form;
	}

	@Nullable
	@Override
	public JComponent getPreferredFocusedComponent() {
		JComponent component = super.getPreferredFocusedComponent();
		if (component != null) {
			return component;
		}
		return matcherField;
	}

	@Override
	public boolean showAndGet() {
		boolean isOk = super.showAndGet();
		if (isOk) {
			getPathConverter().setPatter(getPattern());
			getPathConverter().setReplacement(getReplacement());
		}
		return isOk;
	}

	@Nullable
	@Override
	protected ValidationInfo doValidate() {
		String matcherTest = matcherField.getText();
		try {
			Pattern.compile(matcherTest);
		} catch (Exception e) {
			return new ValidationInfo("Pattern to match invalid.", matcherField);
		}

		return super.doValidate();
	}

	private String getPattern() {
		return matcherField.getText();
	}

	private String getReplacement() {
		return replacementField.getText();
	}
}
